﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.Utilities;

namespace SP.Docs.Migrator
{
    public partial class RelinkDocs : Form
    {
        private string logPath = Path.Combine(Settings.LogFolder, "docsrelink.txt");
        public RelinkDocs()
        {
            InitializeComponent();
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void LogEntry(string msg)
        {
            try
            {
                StreamWriter wr = new StreamWriter(logPath, true);
                wr.WriteLine(DateTime.Now + " : " + msg);
                wr.Close();
            }
            catch { }
        }
        private void LoadProgressBar(int count)
        {
            this.progBar.Maximum = count; this.progBar.Minimum = 0;
            this.progBar.Value = 0;
        }
        private void UpdateProgressBar(int value)
        {
            this.progBar.Value = value;
            this.progBar.Update();
        }
        private void cmdUpdate_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;
            LogEntry("Opening site...");
            using (SPSite site = new SPSite(this.txtSiteUrl.Text))
            {
                LogEntry("Opening web...");
                using (SPWeb spWeb = site.OpenWeb())
                {
                    LogEntry("Loading list...");
                    SPList spList = spWeb.Lists[txtLibName.Text];
                    SPDocumentLibrary spContainingDocLib = (SPDocumentLibrary)spList;
                    String strSolutionURL = SPHttpUtility.UrlPathEncode(spWeb.Url + "/" + spContainingDocLib.DocumentTemplateUrl,
                                                                 true);
                    LogEntry("Starting iteration items...");
                    LoadProgressBar(spList.Items.Count);
                    for(int i = 0; i < spList.Items.Count; i ++)
                    {
                        SPListItem spItem = spList.Items[i];
                        UpdateProgressBar(i + 1);
                        LogEntry("Processing item : " + spItem.Name);
                        try
                        {
                            SPFieldCollection spFields = spItem.Fields;
                            #region force check in code
                            /*
                            if (spList.ForceCheckout)
                            {
                                SPContext currentSPContext = SPContext.Current;
                                SPWeb currentWeb = currentSPContext.Web;
                                SPUser currentUser = currentWeb.CurrentUser;
                                SPFile currentFile = spItem.File;
                                if ((currentFile == null))
                                {
                                    bForceCheckoutError = true;
                                    continue;
                                }
                                else
                                {
                                    try
                                    {
                                        SPUser checkoutUser = currentFile.CheckedOutBy;
                                        if (checkoutUser == null || checkoutUser.ID != currentUser.ID)
                                        {
                                            bForceCheckoutError = true;
                                            continue;
                                        }
                                    }
                                    catch
                                    {
                                        bForceCheckoutError = true;
                                        continue;
                                    }
                                }
                            }
                             * */
                            #endregion
                            foreach (SPField spField in spFields)
                            {
                                if (spField.Type != SPFieldType.Computed &&
                                    spField.Type != SPFieldType.Invalid && !spField.ReadOnlyField)
                                {
                                    try
                                    {
                                        spItem[spField.InternalName] = spItem[spField.InternalName];
                                    }
                                    catch (Exception exx)
                                    {
                                    }
                                }
                            }
                            SPContentType spContentType = spList.ContentTypes[comboContentTypes.Text];
                            if (spContentType != null)
                            {
                                if (spContentType.DocumentTemplate.StartsWith("http://") ||
                                spContentType.DocumentTemplate.StartsWith("https://"))
                                {
                                    spItem["TemplateUrl"] = SPHttpUtility.UrlPathEncode(spContentType.DocumentTemplate, true);
                                }
                                else if (spContentType.DocumentTemplate.StartsWith("/"))
                                {
                                    spItem["TemplateUrl"] = SPHttpUtility.UrlPathEncode(spWeb.Site.MakeFullUrl(spContentType.DocumentTemplate), true);
                                }
                                else
                                {
                                    spItem["TemplateUrl"] = SPHttpUtility.UrlPathEncode(spWeb.Url + '/' + spList.RootFolder + '/' + spContentType.DocumentTemplate, true);
                                }
                                spItem["ContentTypeId"] = spContentType.Id;
                                spItem["Content Type"] = spContentType.Name;
                            }
                            else spItem["TemplateUrl"] = strSolutionURL;
                            spItem.SystemUpdate();
                        }
                        catch(Exception ex) 
                        {
                            LogEntry("exception occured while processing item. " + spItem.Name + ". Exception: " + ex.Message);
                        }
                    }
                    LogEntry("Iteration finished...");
                }
            }
            LogEntry("Operation finished...");
            System.Windows.Forms.Cursor.Current = Cursors.Default;
        }

        private void cmdBrowseContentTypes_Click(object sender, EventArgs e)
        {
            comboContentTypes.Items.Clear();
            System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;

            try
            {
                using (SPSite site = new SPSite(this.txtSiteUrl.Text))
                {
                    using (SPWeb spWeb = site.OpenWeb())
                    {
                        SPList spList = spWeb.Lists[txtLibName.Text];
                        foreach (SPContentType ctype in spList.ContentTypes)
                        {
                            comboContentTypes.Items.Add(ctype.Name);
                        }
                    }
                }
            }
            catch (Exception ex) { LogEntry("Exception has occured while pulling the content types." + ex.Message); }
            System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;
        }
    }
}
